package com.king.base.service.dict.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.king.base.auth.utils.EntityUtils;
import com.king.base.domain.dict.DictType;
import com.king.base.msg.BaseResponseEntity;
import com.king.base.mapper.dict.DictTypeMapper;
import com.king.base.service.dict.DictService;
import com.king.base.service.dict.DictValueService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Spur
 * @date 2019/6/24
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DictServiceImpl extends ServiceImpl<DictTypeMapper,DictType> implements DictService {
    @Autowired
    private DictValueService dictValueService;
    @Override
    public IPage<DictType> page(Pageable pageable, DictType dictType) {
        Page<DictType> page=new Page<DictType>(pageable.getPageNumber(),pageable.getPageSize());
        return page.setRecords(baseMapper.page(page, dictType));
    }

    @Override
    public boolean checkUnique(DictType dictType) {
        return baseMapper.checkUniqueCode(dictType)>0;
    }

    @Override
    public void delete(String id,String dictCode) {
        //删除字典
        baseMapper.deleteById(id);
        //删除明细
        dictValueService.deleteByDictCode(dictCode);
    }

    @Override
    public BaseResponseEntity createOrUpdate(DictType entity) {

        if(checkUnique(entity)){
            return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"字典编码重复:"+entity.getDictCode());
        }
        if(StringUtils.isNotBlank(entity.getDictId())){
            EntityUtils.setUpdatedInfo(entity);
        }else{
            EntityUtils.setCreateAndUpdateInfo(entity);
        }
        super.saveOrUpdate(entity);
        return new BaseResponseEntity("创建成功!");
    }
}
